﻿using System;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;

namespace NMA.Infrastructure.NHibernate.Service.Specification
{
    using NMA.Domain.Shared.Specification;
    using NMA.Infrastructure.NHibernate.Service.Event;
    using NMA.Domain.Model.Repository;
    using NMA.Infrastructure.NHibernate.Container;
    using NMA.Infrastructure.Logging;    
    using NMA.Domain.Model;
    using NMA.Infrastructure.DBC;

    public class CategoryAuditSpecification : AbstractSpecification<AuditEvent>
    {
        private readonly IUserRepository _userRepository = null;        

        public CategoryAuditSpecification() :this(IoC.GetInstance<IUserRepository>())
        { }

        public CategoryAuditSpecification(IUserRepository userRepository)
        {
            _userRepository = userRepository;
        }

        /// <summary>
        /// Only audit when user name is existed in database
        /// and the audit date is larger than current date
        /// </summary>
        /// <param name="catEvent">Audit event object</param>
        /// <returns>true if satisfied the condition or false if else</returns>
        public override bool IsSatisfiedBy(AuditEvent catEvent)
        {
            Check.Assert(catEvent != null, "AuditEvent's object is null");

            bool result = false;            

            try
            {               
                IEnumerable<IUser> users = _userRepository.GetBy(
                    x => string.Compare(x.UserName, catEvent.UserName) == 0
                    && DateTime.Now.CompareTo(catEvent.DateEvent) >= 0);

                if (users == null)
                    throw new Exception("User's object is null");

                result = users.Any();                
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return result;
        }
    }
}